package com.iweb.service;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.iweb.mapper.UserMapper;
import com.iweb.model.User;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * 南京艾瑞
 * 作者: jack
 * 时间: 2020-06-29 15:26
 * 描述: UserService
 */
@Service
public class UserService {

    @Resource
    private UserMapper userMapper;

    public List<User> findAll() {
        return userMapper.selectList(null);
    }

    public User findById(String id) {
        return userMapper.selectById(id);
    }

    public User updateById(User user) {
        userMapper.updateById(user);
        return userMapper.selectById(user.getId());
    }

    public void deleteById(String id) {
        userMapper.deleteById(id);
    }

    @Transactional(rollbackFor = RuntimeException.class)
    public User addUser(User user) {
        // id使用分布式唯一id
        userMapper.insert(user);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", user.getUsername());
        Integer count = userMapper.selectCount(queryWrapper);
        if (count > 1) {
            throw new RuntimeException("用户重复");
        }
        return user;
    }

    public List<User> findUsersByPage(Integer current, Integer size) {
        IPage<User> page = new Page<>(current, size);
        IPage<User> userIPage = userMapper.selectPage(page, null);
        System.out.println("总条数:" + userIPage.getTotal());
        return userIPage.getRecords();
    }

    public List<User> findByUser(User user) {
        Wrapper<User> queryWrapper = new QueryWrapper<>(user);
        // 非 == 比较
        // QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        // queryWrapper.like("数据库的列名", user.getPassword());
        List<User> users = userMapper.selectList(queryWrapper);
        return users;
    }
}
